package com.woniu.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniu.entity.FlowerCart;
import com.woniu.mapper.FlowerCartMapper;
import com.woniu.service.FlowerCartService;
import com.woniu.vo.CartVoCZT;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class FlowerCartServiceImpl implements FlowerCartService {
    @Resource
    private FlowerCartMapper fcm;

    @Override
    public PageInfo<CartVoCZT> selectAllCartByAccountId(int accountId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<CartVoCZT> list = fcm.selectAllCartByAccountId(accountId);
        return new PageInfo<>(list);
    }

    @Override
    public int updateBuyCountByCartId(int buyCount, int cartId) {
        FlowerCart flowerCart = new FlowerCart();
        flowerCart.setCartId(cartId);
        flowerCart.setBuyCount(buyCount);
        flowerCart.setUpdateTime(new Date());
        return fcm.updateByPrimaryKeySelective(flowerCart);
    }

    @Override
    public int deleteCartByCartId(int cartId) {
        FlowerCart flowerCart = new FlowerCart();
        flowerCart.setCartId(cartId);
        flowerCart.setIsDelete((byte) 1);
        flowerCart.setUpdateTime(new Date());
        return fcm.updateByPrimaryKeySelective(flowerCart);
    }

    @Override
    public int deleteMoreCart(int[] cartIds) {
        int delete = 0;
        for (int cartId : cartIds) {
            FlowerCart flowerCart = new FlowerCart();
            flowerCart.setCartId(cartId);
            flowerCart.setIsDelete((byte) 1);
            flowerCart.setUpdateTime(new Date());
            delete = fcm.updateByPrimaryKeySelective(flowerCart);
            if (delete == 0) {
                break;
            }
        }
        return delete;
    }

    @Override
    public int insertCartByAccountId(int accountId, int flowerId, int buyCount) {
        //核查是否在购物车中已有
        Example example = new Example(FlowerCart.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("accountId", accountId);
        criteria.andEqualTo("flowerId", flowerId);
        criteria.andEqualTo("isDelete",0 );
        FlowerCart temp = fcm.selectOneByExample(example);
        if (temp != null) {
            temp.setBuyCount(temp.getBuyCount() + buyCount);
            temp.setUpdateTime(new Date());
            return fcm.updateByPrimaryKeySelective(temp);
        } else {
            FlowerCart flowerCart = new FlowerCart();
            flowerCart.setAccountId(accountId);
            flowerCart.setFlowerId(flowerId);
            flowerCart.setBuyCount(buyCount);
            flowerCart.setCreateTime(new Date());
            return fcm.insertSelective(flowerCart);
        }
    }
}
